<template>
  <va-modal v-model="isVisible" hide-default-actions title="登录">
    <div class="login-form">
      <va-alert v-if="authError" color="danger" icon="error">
        {{ authError }}
      </va-alert>
      
      <form @submit.prevent="handleLogin">
        <va-input
          v-model="username"
          label="用户名"
          class="mb-4"
          placeholder="输入用户名"
          :error="!!usernameError"
          :error-messages="usernameError"
          @update:modelValue="usernameError = ''"
          required
        />
        
        <va-input
          v-model="password"
          label="密码"
          class="mb-4"
          placeholder="输入密码"
          type="password"
          :error="!!passwordError"
          :error-messages="passwordError"
          @update:modelValue="passwordError = ''"
          required
        />
        
        <div class="actions">
          <va-button type="submit" color="primary" :loading="isLoading">
            登录
          </va-button>
          <va-button @click="closeDialog" flat>
            取消
          </va-button>
        </div>
      </form>
      
      <div class="info-text">
        <p>默认管理员账户：admin / memeking</p>
      </div>
    </div>
  </va-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAuth } from '../composables/useAuth'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'login-success'])

const { login, isLoading, error: authError } = useAuth()

const username = ref('')
const password = ref('')
const usernameError = ref('')
const passwordError = ref('')

const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

watch(() => props.modelValue, (newVal) => {
  // Reset form when dialog opens
  if (newVal) {
    username.value = ''
    password.value = ''
    usernameError.value = ''
    passwordError.value = ''
  }
})

const handleLogin = async () => {
  // Validate input
  let isValid = true
  
  if (!username.value) {
    usernameError.value = '请输入用户名'
    isValid = false
  }
  
  if (!password.value) {
    passwordError.value = '请输入密码'
    isValid = false
  }
  
  if (!isValid) return
  
  try {
    await login(username.value, password.value)
    closeDialog()
    emit('login-success')
  } catch (error) {
    // Error is already handled in the composable
  }
}

const closeDialog = () => {
  isVisible.value = false
}
</script>

<style scoped>
.login-form {
  padding: 1rem 0;
}

.mb-4 {
  margin-bottom: 1rem;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.info-text {
  margin-top: 1.5rem;
  font-size: 0.875rem;
  color: var(--text-secondary);
}
</style> 